"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 导入导出、备份恢复工具支持M*兼容性
Case Name   : 使用gs_dump导出表，表含兼容M侧浮点类型
Create At   : 2023.05.04
Owner       : @wan005
Description :
    1.创建兼容b库
    2.兼容b库下建表，含兼容浮点类型
    3.使用gs_dump工具导出表为tar格式
    4.导入之前导出的数据到新库
    5.连接导入库查询
    6.清理环境
Expect      :
    1.成功
    2.成功
    3.成功
    4.成功
    5.成功
    6.成功
History     :
"""

import os
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro


class GsDump0003(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.sh_primary = CommonSH('PrimaryDbUser')
        self.dbuser_node = Node('PrimaryDbUser')
        self.constant = Constant()
        self.com = Common()
        self.db_name = "db_dump_0003"
        self.db_name_01 = "db_dump_0003_01"
        self.tb_name = "tb_dump_0003"
        self.dump_path = os.path.join(macro.DB_BACKUP_PATH, 'dump0003')
        self.expect_result_dict = {
            'Column': ['c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9',
                       'c10', 'c11', 'c12', 'c13', 'c14', 'c15', 'c16', 'c17',
                       'c18'],
            'Type': ['numeric(10,3)', 'numeric(10,3)', 'numeric(10,3)',
                     'numeric(10,3)', 'numeric(10,3)', 'numeric(10,3)',
                     'numeric(10,3)', 'numeric(10,3)', 'numeric(10,3)',
                     'numeric(10,0)', 'numeric(10,0)', 'numeric(10,0)',
                     'numeric(10,0)', 'real', 'double precision',
                     'double precision', 'real', 'number']}

    def test_server_tools(self):
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        text = '----step1: 创建兼容b库 expect: 成功----'
        self.log.info(text)
        sql_cmd = f"drop database if exists {self.db_name};" \
                  f"create database {self.db_name} dbcompatibility 'b';" \
                  f"drop database if exists {self.db_name_01};" \
                  f"create database {self.db_name_01} dbcompatibility 'b';"
        self.log.info(sql_cmd)
        sql_result = self.sh_primary.execut_db_sql(sql_cmd)
        self.log.info(sql_result)
        self.assertEqual(2, sql_result.count(
            self.constant.CREATE_DATABASE_SUCCESS))

        text = '----step2: 兼容b库下建表，含兼容浮点类型 expect: 成功----'
        self.log.info(text)
        sql_cmd = f"drop table if exists {self.tb_name};" \
                  f"create table {self.tb_name}(" \
                  f"c1 fixed(10,3)," \
                  f"c2 decimal(10,3)," \
                  f"c3 dec(10,3)," \
                  f"c4 numeric(10,3)," \
                  f"c5 float(10,3)," \
                  f"c6 double(10,3)," \
                  f"c7 double precision(10,3)," \
                  f"c8 real(10,3)," \
                  f"c9 number(10,3)," \
                  f"c10 fixed," \
                  f"c11 decimal," \
                  f"c12 dec," \
                  f"c13 numeric," \
                  f"c14 float," \
                  f"c15 double," \
                  f"c16 double precision," \
                  f"c17 real," \
                  f"c18 number)engine='字符';" \
                  f"insert {self.tb_name} values(25.5623,65.535,42.94967295," \
                  f"42.94967295,42.94967295,18.4467,12.8,32.767,214.748," \
                  f"214.74,21.47,92.25,21.47,21.47,21.47,21.47,12.8,12.8);"
        self.log.info(sql_cmd)
        sql_result = self.sh_primary.execut_db_sql(sql_cmd,
                                                   dbname=self.db_name)
        self.log.info(sql_result)
        self.assertIn(self.constant.TABLE_CREATE_SUCCESS, sql_result)
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, sql_result)

        text = '----step3: 使用gs_dump工具导出表为tar格式 expect: 成功----'
        self.log.info(text)
        gs_dump_cmd = f"source {macro.DB_ENV_PATH};" \
                      f"gs_dump " \
                      f"-p {self.dbuser_node.db_port} " \
                      f"{self.db_name} -F t " \
                      f"-f {self.dump_path}"
        self.log.info(gs_dump_cmd)
        dump_msg = self.dbuser_node.sh(gs_dump_cmd).result()
        self.log.info(dump_msg)
        self.assertIn(f"dump database {self.db_name} successfully",
                      dump_msg, '执行失败:' + text)

        text = '----step4: 导入之前导出的数据到新库 expect: 成功----'
        self.log.info(text)
        gs_restore_cmd = f"source {macro.DB_ENV_PATH};" \
                         f"gs_restore -p {self.dbuser_node.db_port} " \
                         f"-d {self.db_name_01} " \
                         f"{self.dump_path}"
        self.log.info(gs_restore_cmd)
        restore_msg = self.dbuser_node.sh(gs_restore_cmd).result()
        self.log.info(restore_msg)
        self.assertIn(self.constant.RESTORE_SUCCESS_MSG, restore_msg,
                      '执行失败:' + text)

        text = '----step5: 连接导入库查询 expect: 成功----'
        self.log.info(text)
        sql_cmd = f"\d+ {self.tb_name};"
        self.log.info(sql_cmd)
        sql_result = self.sh_primary.execut_db_sql(sql_cmd,
                                                   dbname=self.db_name_01)
        self.log.info(sql_result)
        result_dict = self.com.format_sql_result(sql_result)
        self.log.info(result_dict)
        del_key = ['Modifiers', 'Storage', 'Stats target', 'Description']
        for k in del_key:
            result_dict.pop(k, None)
        self.assertDictEqual(self.expect_result_dict, result_dict)

        sql_cmd = f"select * from {self.tb_name};"
        sql_result = self.sh_primary.execut_db_sql(sql_cmd,
                                                   dbname=self.db_name_01)
        self.log.info(sql_result)
        msg_lis = ['25.562', '65.535', '42.950', '42.950', '42.950',
                   '18.447', '12.800', '32.767', '214.748',
                   '215', '21', '92', '21', '21.47', '21.47', '21.47', '12.8',
                   '12.8']
        for msg in msg_lis:
            self.assertIn(msg, sql_result, '查询失败')

    def tearDown(self):
        text = '---step6: 清理环境 expect: 成功----'
        self.log.info(text)
        sql_cmd = f"drop database if exists {self.db_name};" \
                  f"drop database if exists {self.db_name_01};"
        self.log.info(sql_cmd)
        sql_result = self.sh_primary.execut_db_sql(sql_cmd,
                                                   dbname='postgres')
        self.log.info(sql_result)
        rm_cmd = f"rm -rf {self.dump_path}"
        self.log.info(rm_cmd)
        rm_msg = self.dbuser_node.sh(rm_cmd).result()
        self.log.info(rm_msg)
        self.assertEqual(2,
                         sql_result.count(self.constant.DROP_DATABASE_SUCCESS))
        self.assertEqual('', rm_msg)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
